from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import JsonResponse
from django.db.models import Count
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage

from .models import Category, Tag, Article, Section, Translation
from .forms import RecommendForm, TranslateForm


def index(request):
    """
    首页
    """
    categories = Category.objects.filter(article__status=Article.TRANSLATED).annotate(num_articles=Count('article'))

    articles = Article.objects.filter(status=Article.TRANSLATED).order_by('-translated_date')[:17]

    untranslated = Article.objects.filter(status=Article.APPROVED)[:10]

    tags = Tag.objects.filter(article__status=Article.TRANSLATED).annotate(num_articles=Count('article')).order_by('-num_articles')[:8]

    recommendForm = RecommendForm()

    return render(request, 'translations/index.html', 
                        {'categories': categories, 'tags': tags, 'articles': articles, 'untranslated': untranslated, 'recommendForm': recommendForm})


def list(request, category_id=None):
    """
    文章列表
    """
    categories = Category.objects.filter(article__status=Article.TRANSLATED).annotate(num_articles=Count('article'))

    articles = Article.objects.filter(status=Article.TRANSLATED)

    sort = request.GET.get('sort')
    if sort == 'views':
        articles = articles.order_by('-view_count')
    else:
        articles = articles.order_by('-translated_date')

    current_category = None
    if category_id != None:
        current_category = get_object_or_404(Category, pk=category_id)
        articles = articles.filter(category=current_category)

    paginator = Paginator(articles, 16)
    page = request.GET.get('page')
    try:
        articles = paginator.page(page)
    except PageNotAnInteger:
        articles = paginator.page(1)
    except EmptyPage:
        articles = paginator.page(paginator.num_pages)

    sort_urls = {}
    url_get_params = request.GET.copy()
    url_get_params['sort'] = 'published'
    sort_urls['published'] = '?' + url_get_params.urlencode()
    url_get_params['sort'] = 'views'
    sort_urls['views'] = '?' + url_get_params.urlencode()

    return render(request, 'translations/list.html', {'current_category': current_category, 'categories': categories,
                                                            'articles': articles, 'sort_urls': sort_urls})


def untranslated(request):
    untranslated = Article.objects.filter(status=Article.APPROVED)

    sort = request.GET.get('sort')
    if sort == 'schedule':
        untranslated = untranslated.order_by('-translate_rate')

    paginator = Paginator(untranslated, 16)
    page = request.GET.get('page')
    try:
        untranslated = paginator.page(page)
    except PageNotAnInteger:
        untranslated = paginator.page(1)
    except EmptyPage:
        untranslated = paginator.page(paginator.num_pages)

    sort_urls = {}
    url_get_params = request.GET.copy()
    url_get_params['sort'] = 'recommend'
    sort_urls['recommend'] = '?' + url_get_params.urlencode()
    url_get_params['sort'] = 'schedule'
    sort_urls['schedule'] = '?' + url_get_params.urlencode()

    recommendForm = RecommendForm()

    return render(request, 'translations/untranslated.html', {'untranslated': untranslated, 'sort_urls': sort_urls, 'recommendForm': recommendForm})


def tags(request):
    tags = Tag.objects.filter(article__status=Article.TRANSLATED).annotate(num_articles=Count('article')).order_by('-num_articles')

    paginator = Paginator(tags, 80)
    page = request.GET.get('page')
    try:
        tags = paginator.page(page)
    except PageNotAnInteger:
        tags = paginator.page(1)
    except EmptyPage:
        tags = paginator.page(paginator.num_pages)

    return render(request, 'translations/tags.html', {'tags': tags})


def tag(request, tag_id):
    tag = get_object_or_404(Tag, pk=tag_id)
    articles = tag.article_set.all()

    paginator = Paginator(articles, 16)
    page = request.GET.get('page')
    try:
        articles = paginator.page(page)
    except PageNotAnInteger:
        articles = paginator.page(1)
    except EmptyPage:
        articles = paginator.page(paginator.num_pages)

    hot_tags = Tag.objects.filter(article__status=Article.TRANSLATED).annotate(num_articles=Count('article')).order_by('-num_articles')[:8]
    
    return render(request, 'translations/tag.html', {'tag': tag, 'hot_tags': hot_tags, 'articles': articles})


def detail(request, article_id):
    """
    文章详细页
    """
    article = get_object_or_404(Article, pk=article_id)
    article.update_view_count()

    sections = article.section_set.all()
    paginator = Paginator(sections, 10)
    page = request.GET.get('page')
    try:
        sections = paginator.page(page)
    except PageNotAnInteger:
        sections = paginator.page(1)
    except EmptyPage:
        sections = paginator.page(paginator.num_pages)

    translators = set()
    for section in article.section_set.all():
        for translation in section.translation_set.all():
            translators.add(translation.translator)

    mode_urls = {}
    url_get_params = request.GET.copy()
    url_get_params['mode'] = 'ch'
    mode_urls['ch'] = '?' + url_get_params.urlencode()
    url_get_params['mode'] = 'en'
    mode_urls['en'] = '?' + url_get_params.urlencode()
    url_get_params['mode'] = 'contrast'
    mode_urls['contrast'] = '?' + url_get_params.urlencode()

    mode = request.GET.get('mode', 'ch')
    
    return render(request, 'translations/detail.html', {'article': article, 'sections': sections, 'translators': translators, 'mode_urls': mode_urls, 'mode': mode})


@login_required
def recommend(request):
    """
    投递原文
    """
    if request.is_ajax() and request.method == 'POST':
        f = RecommendForm(request.POST)
        if f.is_valid():
            new_article = f.save(commit=False)
            new_article.recommend_user = request.user
            new_article.save()
            return JsonResponse({'success': 'ok'});
    else:
        raise Http404


@login_required
def translate(request, section_id):
    """
    原文翻译
    """
    s = get_object_or_404(Section, pk=section_id)
    if request.method == 'POST':
        f = TranslateForm(request.POST)
        if f.is_valid():
            new_translation = Translation()
            new_translation.translator = request.user
            new_translation.content = f.cleaned_data.get('content')
            new_translation.section = s
            new_translation.save()
            s.article.update_translate_rate()
            return redirect(reverse('translations:detail', args=(s.article.id,)))
    else:
        f = TranslateForm()
    above_s = s.article.section_set.filter(index=s.index-1).first()
    next_s = s.article.section_set.filter(index=s.index+1).first()
    return render(request, 'translations/translate.html', {'form': f, 'section': s, 'above_s': above_s, 'next_s': next_s})
